<template>
	<div style="position: relative;">
		<el-card shadow="hover">
			<GoBack @back="goBack" />
			<div class="pa40">
				<el-steps :active="active" simple finish-status="success">
					<el-step title="基本信息" icon="el-icon-edit" />
					<el-step title="其他信息" icon="el-icon-edit" />
				</el-steps>
				<el-form ref="form" :model="formData.data" :rules="formData.rules" label-width="110px" class="mt30">
					<div v-if="active === 0">
						<el-form-item ref="goodsName" label="商品名称" prop="goodsName">
							<el-input v-model.trim="formData.data.goodsName" style="width: 70%;" maxlength="20" show-word-limit placeholder="请输入商品名称" />
						</el-form-item>
						<el-form-item ref="brandName" label="商品品牌" prop="brandName">
							<el-input v-model.trim="formData.data.brandName" style="width: 70%;" maxlength="20" show-word-limit placeholder="请输入商品品牌" />
						</el-form-item>
						<el-form-item ref="categoryId" label="商品分类" prop="categoryId">
							<el-cascader
								style="width: 70%;"
								v-model="formData.data.categoryId"
								:options="typeList"
								placeholder="请选择商品分类"
								:props="{ expandTrigger: 'hover', emitPath: false, value: 'id', label: 'name', children: 'list' }"
								clearable
							></el-cascader>
						</el-form-item>
						<el-form-item ref="yieldly" label="商品产地" prop="yieldly">
							<el-cascader
								style="width: 70%;"
								v-model="formData.data.yieldly"
								:options="cityList"
								placeholder="请选择商品产地"
								:props="{ expandTrigger: 'hover', value: 'id', label: 'name' }"
								clearable
							></el-cascader>
						</el-form-item>
						<el-form-item ref="keywords" label="关键字" prop="keywords"><addTags v-model:tags="formData.data.keywords"></addTags></el-form-item>
						<el-form-item ref="desc" label="商品描述" prop="desc">
							<el-input
								v-model.trim="formData.data.desc"
								placeholder="填写点什么吧"
								style="width: 70%;"
								type="textarea"
								:autosize="{ minRows: 5, maxRows: 10 }"
								maxlength="100"
								show-word-limit
							/>
						</el-form-item>
						<el-form-item ref="price" label="商品售价" prop="price">
							<el-input v-model.trim="formData.data.price" style="width: 70%;" placeholder="请设置商品售价" @input="filterNum(formData.data, 'price', $event)" />
						</el-form-item>
						<el-form-item ref="marketPrice" label="市场价" prop="marketPrice">
							<el-input
								v-model.trim="formData.data.marketPrice"
								style="width: 70%;"
								placeholder="请设置市场价"
								@input="filterNum(formData.data, 'marketPrice', $event)"
							/>
						</el-form-item>
						<el-form-item ref="costPrice" label="成本价" prop="costPrice">
							<el-input
								v-model.trim="formData.data.costPrice"
								style="width: 70%;"
								placeholder="请设置成本价"
								@input="filterNum(formData.data, 'costPrice', $event)"
							/>
						</el-form-item>
						<el-form-item ref="inventory" label="商品库存" prop="inventory">
							<el-input
								v-model.trim="formData.data.inventory"
								style="width: 70%;"
								placeholder="请设置商品库存"
								@input="filterNum(formData.data, 'inventory', $event)"
							/>
						</el-form-item>
						<el-form-item ref="inventoryWarning" label="库存预警值" prop="inventoryWarning">
							<el-input
								v-model.trim="formData.data.inventoryWarning"
								style="width: 70%;"
								placeholder="请设置库存预警值"
								@input="filterNum(formData.data, 'inventoryWarning', $event)"
							/>
						</el-form-item>
						<el-form-item ref="pic" label="图片上传" prop="pic">
							<UploadImage :limit="6" :fileUrl="formData.data.pic" @input="getPicUrl('pic', $event)">
								<template #other="{file}">
									<span @click="editMainTp(file)">
										<el-tooltip class="item" effect="dark" content="设置为商品主图" placement="top-start"><i class="el-icon-edit"></i></el-tooltip>
									</span>
								</template>
							</UploadImage>
						</el-form-item>
						<el-form-item ref="mainPic" label="商品主图" prop="mainPic" v-if="getMainTps">
							<img style="width:148px;height:148px" :src="getMainTps" alt="" />
						</el-form-item>
						<el-form-item ref="video" label="视频上传" prop="video">
							<UploadImage :fileUrl="formData.data.video" listType="text" @input="getPicUrl('video', $event)" />
						</el-form-item>
						<el-form-item ref="postageType" label="商品运费" prop="postageType">
							<el-radio-group v-model="formData.data.postageType" disabled>
								<el-radio :label="1">固定运费</el-radio>
								<el-radio :label="2">模板运费</el-radio>
								<el-radio :label="3">商家包邮</el-radio>
							</el-radio-group>
						</el-form-item>
						<div v-if="formData.data.postageType === 1">
							<el-form-item ref="postage" label="固定运费" prop="postage">
								<el-input
									v-model.trim="formData.data.postage"
									style="width: 70%;"
									placeholder="请设置固定运费"
									@input="filterNum(formData.data, 'postage', $event)"
								/>
							</el-form-item>
						</div>
						<div v-if="formData.data.postageType === 2">
							<el-form-item ref="postageTemplate" label="模板方式" prop="postageTemplate">
								<el-select v-model="formData.data.postageTemplate" placeholder="请选择">
									<el-option v-for="item in [{ id: 1, name: '三通' }, { id: 2, name: '京东' }]" :key="item.id" :label="item.name" :value="item.id"></el-option>
								</el-select>
							</el-form-item>
						</div>
						<el-form-item ref="isComments" label="是否允许评论" prop="isComments">
							<el-switch v-model="formData.data.isComments" :active-value="1" :inactive-value="2"></el-switch>
						</el-form-item>
						<el-form-item ref="shelvesState" label="是否上架" prop="shelvesState">
							<el-switch v-model="formData.data.shelvesState" :active-value="1" :inactive-value="2"></el-switch>
						</el-form-item>
						<el-form-item ref="state" label="是否显示" prop="state">
							<el-switch v-model="formData.data.state" :active-value="1" :inactive-value="2"></el-switch>
						</el-form-item>
						<el-form-item ref="detailsPhone" label="商品详情" prop="detailsPhone">
							<el-col :span="12">
								<div class="wrapper">
									<div v-show="item.length > 0" v-for="item in formData.data.detailsPhone.split(',')" class="wrapper-list">
										<img :src="getPic(item)" alt="" style="width: 100%;height: 100%;" />
									</div>
									<div class="wrapper-font">{{ formData.data.detailsPhoneDesc }}</div>
								</div>
							</el-col>
							<el-col :span="12" class="ml10">
								<el-input
									v-model.trim="formData.data.detailsPhoneDesc"
									:autosize="{ minRows: 3, maxRows: 5 }"
									type="textarea"
									maxlength="100"
									show-word-limit
									placeholder="添加文字"
									class="mb10"
									style="width: 100%"
								/>
								<UploadImage :limit="20" listType="picture" :fileUrl="formData.data.detailsPhone" @input="getPicUrl('detailsPhone', $event)" />
							</el-col>
						</el-form-item>
						<el-form-item ref="specialDesc" label="助力贴士" prop="specialDesc">
							<el-input
								v-model.trim="formData.data.specialDesc"
								placeholder="填写点什么吧"
								style="width: 70%;"
								type="textarea"
								:autosize="{ minRows: 5, maxRows: 10 }"
								maxlength="100"
								show-word-limit
							/>
						</el-form-item>
					</div>
					<div v-if="active === 1">
						<el-form-item ref="specificationsType" label="属性类型" prop="specificationsType">
							<el-input v-model.trim="formData.data.specificationsType" style="width: 70%;" placeholder="请设置属性类型" />
						</el-form-item>
						<el-form-item ref="specificationsInfo" label="商品规格" prop="specificationsInfo">
							<div class="tableClass">
								<el-table
									:data="formData.data.specificationsInfo ? formData.data.specificationsInfo : []"
									stripe
									max-height="300"
									highlight-current-row
									:header-cell-style="{ color: '#7f8da6', backgroundColor: '#F5F6F8' }"
								>
									<el-table-column prop="specsValue" label="规格" min-width="130">
										<template #default="scope">
											<el-form-item :prop="`specificationsInfo.${scope.$index}.specsValue`" :rules="formData.rules.specsValue">
												<el-input
													v-model.trim="scope.row.specsValue"
													style="width: 100%;"
													placeholder="**/盒"
													@input="filterNum(scope.row, 'specsValue', $event)"
												/>
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column prop="specsPrice1" label="商品售价(￥)" min-width="130">
										<template #default="scope">
											<el-form-item :prop="`specificationsInfo.${scope.$index}.specsPrice1`" :rules="formData.rules.specsPrice1">
												<el-input v-model.trim="scope.row.specsPrice1" style="width: 100%;" @input="filterNum(scope.row, 'specsPrice1', $event)" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column prop="specsPrice2" label="市场价(￥)" min-width="130">
										<template #default="scope">
											<el-form-item :prop="`specificationsInfo.${scope.$index}.specsPrice2`" :rules="formData.rules.specsPrice2">
												<el-input v-model.trim="scope.row.specsPrice2" style="width: 100%;" @input="filterNum(scope.row, 'specsPrice2', $event)" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column prop="specsPrice3" label="成本价(￥)" min-width="130">
										<template #default="scope">
											<el-form-item :prop="`specificationsInfo.${scope.$index}.specsPrice3`" :rules="formData.rules.specsPrice3">
												<el-input v-model.trim="scope.row.specsPrice3" style="width: 100%;" @input="filterNum(scope.row, 'specsPrice3', $event)" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column prop="specsStock" label="库存" min-width="130">
										<template #default="scope">
											<el-form-item :prop="`specificationsInfo.${scope.$index}.specsStock`" :rules="formData.rules.specsStock">
												<el-input v-model.trim="scope.row.specsStock" style="width: 100%;" @input="filterNum(scope.row, 'specsStock', $event)" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column prop="specsStockValue" label="预警值" min-width="130">
										<template #default="scope">
											<el-form-item :prop="`specificationsInfo.${scope.$index}.specsStockValue`" :rules="formData.rules.specsStockValue">
												<el-input v-model.trim="scope.row.specsStockValue" style="width: 100%;" @input="filterNum(scope.row, 'specsStockValue', $event)" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column prop="tag" label="操作" fixed="right" width="130px">
										<template #header>
											<el-button icon="el-icon-plus" size="small" @click="addSpecs">新增规格</el-button>
										</template>
										<template #default="scope">
											<div><el-button type="text" @click="formData.data.specificationsInfo.splice(scope.$index, 1)">删除</el-button></div>
										</template>
									</el-table-column>
								</el-table>
							</div>
						</el-form-item>
						<el-form-item ref="integral" label="获得积分" prop="integral">
							<el-input
								v-model.trim="formData.data.integral"
								style="width: 70%;"
								placeholder="请设置获得积分"
								@input="filterNum(formData.data, 'integral', $event)"
							/>
						</el-form-item>
						<el-form-item ref="comments" label="评论标签" prop="comments"><addTags v-model:tags="formData.data.comments"></addTags></el-form-item>
						<el-form-item ref="storeRemark" label="商家备注" prop="storeRemark">
							<el-input
								v-model.trim="formData.data.storeRemark"
								placeholder="填写点什么吧"
								style="width: 70%;"
								type="textarea"
								:autosize="{ minRows: 5, maxRows: 10 }"
								maxlength="100"
								show-word-limit
							/>
						</el-form-item>
					</div>
					<el-form-item class="mt15">
						<el-button v-show="active !== 0" @click="active -= 1">上一步</el-button>
						<el-button :loading="formData.loading" type="primary" @click="onSubmit">{{ active !== 1 ? '保存，继续下一步' : '完成' }}</el-button>
					</el-form-item>
				</el-form>
			</div>
		</el-card>
	</div>
</template>

<script lang="ts">
import { defineComponent, toRefs, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from '/@/store/index.ts'
import GoBack from '/@/components/GoBack/index.vue'
import UploadImage from '/@/components/UploadImage/index.vue'
import addTags from '/@/components/addTags/index.vue'
import { ElMessage } from 'element-plus'
import { defaultGoodSpecs, defaultGoodListData, getCategoryList, getGoodsInfoById, insertGoods, updateGoods } from '/@/api/good'
import scrollForm from '/@/utils/scrollForm'
import Base64 from '/@/utils/base64'
import { verifiyNumberInteger } from '/@/utils/toolsValidate'
import city from '/@/dictionaries/city.json'
let id = 0
export default defineComponent({
	name: 'goBack',
	components: { GoBack, UploadImage, addTags },
	setup() {
		const store = useStore()
		const router = useRouter()
		const route = useRoute()

		const refs: any = reactive({
			form: null,
			goodsName: null,
			brandName: null,
			categoryId: null,
			yieldly: null,
			price: null,
			costPrice: null,
			inventory: null,
			pic: null,
			postageType: null,
			postage: null,
			postageTemplate: null,
			detailsPhone: null,
			specificationsInfo: null
		})

		const state: any = reactive({
			routeInfo: {},
			active: 0,
			formData: {
				data: JSON.parse(JSON.stringify(defaultGoodListData)),
				loading: false,
				rules: {
					goodsName: [{ required: true, message: '请输入商品名称,1-20个字符', trigger: 'blur' }],
					brandName: [{ required: true, message: '请输入商品品牌,1-20个字符', trigger: 'blur' }],
					categoryId: [{ required: true, message: '请选择商品分类', trigger: ['blur', 'change'] }],
					yieldly: [{ required: true, message: '请选择商品产地', trigger: ['blur', 'change'] }],
					price: [{ required: true, message: '请设置商品价格', trigger: 'blur' }],
					costPrice: [{ required: true, message: '请设置商品成本价', trigger: 'blur' }],
					inventory: [{ required: true, message: '请设置商品库存', trigger: 'blur' }],
					pic: [{ required: true, message: '请上传最少一张图片', trigger: ['blur', 'change'] }],
					postageType: [{ required: true, message: '请选择商品运输方式', trigger: ['blur', 'change'] }],
					postage: [{ required: true, message: '请输入商品固定运费', trigger: 'blur' }],
					postageTemplate: [{ required: true, message: '请选择商品运输模板', trigger: ['blur', 'change'] }],
					detailsPhone: [{ required: true, message: '请添加商品详情图片', trigger: ['blur', 'change'] }],
					specificationsInfo: [{ required: true, message: '商品规格不能为空', trigger: ['blur', 'change'] }],
					specsValue: [{ required: true, message: '请输入规格', trigger: 'blur' }],
					specsPrice1: [{ required: true, message: '请输入商品售价', trigger: 'blur' }],
					specsPrice2: [{ required: true, message: '请输入市场价', trigger: 'blur' }],
					specsPrice3: [{ required: true, message: '请输入成本价', trigger: 'blur' }],
					specsStock: [{ required: true, message: '请输入库存', trigger: 'blur' }],
					specsStockValue: [{ required: true, message: '请输入预警值', trigger: 'blur' }]
				}
			},
			cityList: [],
			typeList: []
		})

		const goBack = () => {
			router.push({
				path: '/good/goodList',
				query: {}
			})
		}

		const getTypeList = () => {
			getCategoryList({}).then(res => {
				const { datas } = res
				state.typeList = getTreeData(datas)
			})
		}

		//递归
		function getTreeData(data) {
			for (var i = 0; i < data.length > 0; i++) {
				if (data[i].list == null || data[i].list.length <= 0) {
					// list若为空数组，则将list设为undefined
					data[i].list = undefined
				} else {
					// list若不为空数组，则继续 递归调用 本方法
					getTreeData(data[i].list)
				}
			}
			return data
		}

		// 正整数
		const filterNum = (row, field, val: string) => {
			row[field] = verifiyNumberInteger(val)
		}

		// 获得图片路径
		const getPicUrl = (field, val) => {
			console.log(field, val)
			if (typeof val === 'string') state.formData.data[field] = val
			if (!state.formData.data.pic.includes(state.formData.data.mainPic)) state.formData.data.mainPic = ''
		}

		// 获得图片路径
		const getPic = val => {
			if (!val) return false
			return store.state.baseServices.baseServices.img_base_url + val
		}

		// 设置主图
		const editMainTp = val => {
			state.formData.data.mainPic = val.name
		}

		const getMainTps = computed(() => {
			if (state.formData.data.mainPic) return store.state.baseServices.baseServices.img_base_url + state.formData.data.mainPic
			return ''
		})

		const addSpecs = () => {
			const newObj = JSON.parse(JSON.stringify(defaultGoodSpecs))
			state.formData.data.specificationsInfo.push(newObj)
		}

		const onSubmit = () => {
			refs.form.validate(async (valid: boolean, object: object) => {
				if (valid) {
					if (state.active === 1) {
						state.formData.loading = true

						const params = JSON.parse(JSON.stringify(state.formData.data))

						params.specificationsInfo = JSON.stringify(params.specificationsInfo)
						params.yieldly = params.yieldly + ''

						if (state.routeInfo.type === 'add') {
							await insertGoods(params).finally(() => {
								state.formData.loading = false
							})
							ElMessage.success('新增成功！')
						} else {
							await updateGoods(params).finally(() => {
								state.formData.loading = false
							})
							ElMessage.success('编辑成功！')
						}

						router.push({
							path: '/good/goodList',
							query: {}
						})
					} else {
						state.active += 1
					}
				} else {
					scrollForm(refs, object, true)
				}
			})
		}

		// 页面加载时
		onMounted(() => {
			state.routeInfo = Base64.decode(route.query.info)
			console.log(state.routeInfo)

			state.cityList = city

			// 获取分类数据
			getTypeList()

			if (state.routeInfo.type === 'edit') {
				getGoodsInfoById({ id: state.routeInfo.id }).then(res => {
					const { datas } = res
					state.formData.data = datas

					state.formData.data.specificationsInfo = JSON.parse(state.formData.data.specificationsInfo)
					state.formData.data.yieldly = state.formData.data.yieldly.length > 0 ? state.formData.data.yieldly.split(',') : []
				})
			}
		})
		return {
			goBack,
			filterNum,
			getPic,
			getPicUrl,
			editMainTp,
			getMainTps,
			addSpecs,
			onSubmit,
			...toRefs(refs),
			...toRefs(state)
		}
	}
})
</script>

<style lang="scss" scoped>
:deep(.el-steps--simple) {
	padding: 13px;
	background: #fbfdff;
}

.wrapper {
	display: grid;
	position: relative;
	border-radius: 5px;
	border: 1px dashed #d9d9d9;
	grid-template-columns: 100px 100px 100px;
	grid-template-rows: 100px 100px 100px;
}
.wrapper-list {
	background: #eee;
	border: 1px solid #f4f4f4;
}
.wrapper-font {
	position: absolute;
	text-align: center;
	width: 100%;
	top: 10%;
}
.tableClass {
	padding: 12px;
	border-radius: 4px;
	border: 1px solid #cdd4df;
}
</style>
